#include "gui.h"
#include "aggregaty.h"
#include <QHeaderView>

#define ROW_PADDING 6

Gui::Gui(QWidget* parent) 
	: QWidget(parent)
{
	setupUi(this);
	QSettings * qSettings = *gAggregatyInstance->settings;
	if (qSettings == NULL) return;

	table->horizontalHeader()->setStretchLastSection(true);

	table->setSortingEnabled(false);
	int count = qSettings->beginReadArray("aggregaty/subs");
	table->setRowCount(count);
	for(int i = 0; i < count; ++i) {
		qSettings->setArrayIndex(i);
		table->setItem(i, 0, new QTableWidgetItem(qSettings->value("name").toString()));
		table->setItem(i, 1, new QTableWidgetItem(qSettings->value("url").toString()));
		table->setItem(i, 2, new QTableWidgetItem(qSettings->value("interval").toString()));
		table->setItem(i, 3, new QTableWidgetItem(qSettings->value("user").toString()));
		table->setItem(i, 4, new QTableWidgetItem(qSettings->value("passwd").toString()));
		table->verticalHeader()->resizeSection(i, table->verticalHeader()->fontMetrics().height() + ROW_PADDING);
	}
	qSettings->endArray();
	table->setSortingEnabled(true);

	connect(tableNew, SIGNAL(clicked(bool)), this, SLOT(newRow(void)));
	connect(tableRemove, SIGNAL(clicked(bool)), this, SLOT(remRow(void)));

}

void Gui::writeOptions()
{
	QSettings* qSettings = *gAggregatyInstance->settings;
	if (qSettings == NULL) return;

	qSettings->beginWriteArray("aggregaty/subs");
	for(int i = 0; i < table->rowCount(); ++i) {
		if (table->item(i,0) == NULL || table->item(i,1) == NULL) continue;
		if (table->item(i,0)->text() == "" || table->item(i,1)->text() == "") continue;
		qSettings->setArrayIndex(i);
		qSettings->setValue("name", table->item(i, 0)->text());
		qSettings->setValue("url", table->item(i, 1)->text());
		qSettings->setValue("interval", table->item(i, 2)->text());
		if (table->item(i,3) == NULL)
			qSettings->setValue("user", "");
		else
			qSettings->setValue("user", table->item(i, 3)->text());
		if (table->item(i,4) == NULL)
			qSettings->setValue("passwd", "");
		else
			qSettings->setValue("passwd", table->item(i, 4)->text());
	}
	qSettings->endArray();
}

void Gui::newRow() 
{
	table->insertRow(table->rowCount());
	table->setCurrentCell(table->rowCount()-1, 0);
	table->verticalHeader()->resizeSection(table->rowCount()-1, table->verticalHeader()->fontMetrics().height() + ROW_PADDING);
}

void Gui::remRow()
{
	if (table->currentRow() != -1)
		table->removeRow(table->currentRow());
}